package com.example.springboot.excel;

import com.example.springboot.excel.poi.ExcelPoiUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * <p>
 * </p>
 *
 * @author Zero
 * @since 2019/6/14
 */
@RestController
public class ExampleController {

    @GetMapping("/")
    public String welcome() {
        return "Welcome!";
    }

    @PostMapping("/upload")
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        String msg;
        if (file != null) {
            byte[] bytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            int indexOf = originalFilename.lastIndexOf(".");
            String extend = originalFilename.substring(indexOf);
            String strPath = "upload";
            File path = new File(strPath);
            if (!path.exists()) {
                path.mkdirs();
            }
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(strPath).append("/").append("newFile").append(extend);
            File name = new File(stringBuilder.toString());
            FileCopyUtils.copy(bytes, name);
            msg = "上传成功：" + stringBuilder.toString();
        } else {
            msg = "文件为空";
        }
        return msg;
    }

    @PostMapping("/excelImport")
    public String excelImport(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        String msg;
        if (file != null) {
            ExcelPoiUtils.convert(file);
            // TODO
            msg = "导入成功：" + file.getOriginalFilename();
        } else {
            msg = "文件为空";
        }
        return msg;
    }

}
